﻿'use client';

import { usePlaylist } from '@/app/hooks/use-playlist';
import { HlsPlayer } from '@/lib/video/hls-optimizer';
import Artplayer from 'artplayer';
import type { Option } from 'artplayer/types/option';
import Hls from 'hls.js';
import { useEffect, useRef, useCallback } from 'react';

interface PlayInfo {
  url: string;
  name: string;
}

interface VideoPlayerProps {
  playList: PlayInfo[];
  initialIndex?: number;
  videoId?: number;
  onEpisodeChange?: (index: number) => void;
}

// 用于检测是否是m3u8链接
function isM3u8(url: string): boolean {
  return url.includes('.m3u8');
}

// 使用优化的HLS加载器
function optimizedHls(video: HTMLVideoElement, url: string, art: Artplayer) {
  if (isM3u8(url)) {
    if (Hls.isSupported()) {
      // 使用HlsPlayer加载源
      const hls = HlsPlayer.load(video, url);
      
      // 记录并在销毁时清理hls
      art.on('destroy', () => {
        // 不直接销毁，让缓存管理器处理
        if (hls.media === video) {
          hls.detachMedia();
        }
      });

      return true;
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      // 对于iOS设备的原生支持
      video.src = url;
      return true;
    }
  }
  return false;
}

export default function VideoPlayer({ playList, initialIndex = 0, videoId, onEpisodeChange }: VideoPlayerProps) {
  const artRef = useRef<HTMLDivElement>(null);
  const playerRef = useRef<Artplayer | null>(null);
  const lastPlayedUrlRef = useRef<string>('');
  const currentEpisodeIndexRef = useRef<number>(initialIndex);
  const isPlayerReadyRef = useRef<boolean>(false);
  const isSwitchingRef = useRef<boolean>(false);
  const pendingSwitchRef = useRef<{url: string, name: string, index: number} | null>(null);
  const switchQueueRef = useRef<Array<{url: string, name?: string, index?: number, callback?: () => void}>>([]);
  const isProcessingQueueRef = useRef<boolean>(false);

  const { activeIndex, handleEpisodeClick } = usePlaylist({
    playList,
    currentIndex: initialIndex,
    onEpisodeChange: (index) => {
      if (videoId) {
        // 更新URL但不刷新页面
        const newUrl = `/detail/${videoId}-${index}.html`;
        window.history.pushState({ path: newUrl }, '', newUrl);

        // 通知父组件选集已更改
        onEpisodeChange?.(index);
      }
    }
  });

  // 处理切换队列的函数
  const processQueue = useCallback(() => {
    if (isProcessingQueueRef.current || switchQueueRef.current.length === 0) {
      return;
    }

    // 检查播放器是否就绪
    if (!isPlayerReadyRef.current || !playerRef.current || isSwitchingRef.current) {
      console.log('播放器未就绪，等待就绪后处理队列');
      return;
    }

    isProcessingQueueRef.current = true;
    const nextSwitch = switchQueueRef.current.shift();

    if (nextSwitch) {
      console.log('处理队列中的切换请求:', nextSwitch);

      // 执行实际的切换操作
      const success = performSwitch(nextSwitch.url, () => {
        nextSwitch.callback?.();
        isProcessingQueueRef.current = false;

        // 处理队列中的下一个请求
        setTimeout(() => processQueue(), 100);
      });

      if (!success) {
        console.error('队列中的切换请求执行失败');
        isProcessingQueueRef.current = false;
        // 继续处理下一个请求
        setTimeout(() => processQueue(), 100);
      }
    } else {
      isProcessingQueueRef.current = false;
    }
  }, []);

  // 实际执行切换的内部函数
  const performSwitch = useCallback((url: string, callback?: () => void) => {
    if (!playerRef.current) {
      console.log('播放器不存在，无法切换');
      return false;
    }

    if (isSwitchingRef.current) {
      console.log('正在切换中，无法执行新的切换');
      return false;
    }

    try {
      // 标记正在切换
      isSwitchingRef.current = true;

      // 暂停播放
      playerRef.current.pause();

      // 清理旧的事件监听器
      playerRef.current.off('video:loadedmetadata');
      playerRef.current.off('video:loadeddata');
      playerRef.current.off('video:waiting');
      playerRef.current.off('video:canplay');

      // 切换URL
      playerRef.current.switchUrl(url);

      // 添加加载完成监听器
      playerRef.current.on('video:loadeddata', () => {
        console.log('视频切换完成，恢复播放器状态');
        isSwitchingRef.current = false;

        // 重新绑定全屏功能，确保功能正常
        if (playerRef.current) {
          const player = playerRef.current;

          // 重新绑定全屏相关事件
          player.off('fullscreen');
          player.off('fullscreenWeb');

          player.on('fullscreen', (state: boolean) => {
            console.log('全屏状态变化:', state);
          });

          player.on('fullscreenWeb', (state: boolean) => {
            console.log('网页全屏状态变化:', state);
          });
        }

        callback?.();
      });

      // 设置超时保护，防止永远处于切换状态
      setTimeout(() => {
        if (isSwitchingRef.current) {
          console.log('切换超时，强制恢复状态');
          isSwitchingRef.current = false;
          callback?.();
        }
      }, 5000); // 增加超时时间到5秒

      return true;
    } catch (error) {
      console.error('切换URL失败:', error);
      isSwitchingRef.current = false;
      return false;
    }
  }, []);

  // 安全的切换URL方法（改进版）
  const safeSwitch = useCallback((url: string, callback?: () => void) => {
    // 如果播放器不存在，直接返回失败
    if (!playerRef.current) {
      console.log('播放器不存在，无法切换');
      return false;
    }

    // 如果播放器未就绪或正在切换中，添加到队列
    if (!isPlayerReadyRef.current || isSwitchingRef.current) {
      console.log('播放器未就绪或正在切换中，添加到队列等待处理');
      switchQueueRef.current.push({ url, callback });

      // 尝试处理队列（如果播放器就绪的话）
      setTimeout(() => processQueue(), 100);
      return true; // 返回true表示已加入队列
    }

    // 如果播放器就绪且未在切换中，直接执行切换
    return performSwitch(url, callback);
  }, [processQueue, performSwitch]);

  // 销毁和清理播放器实例和资源的函数
  const destroyPlayer = useCallback(() => {
    if (playerRef.current) {
      const videoElement = playerRef.current.video as HTMLVideoElement;

      // 先暂停播放
      playerRef.current.pause();

      // 销毁播放器实例
      playerRef.current.destroy();
      playerRef.current = null;

      // 清理HLS缓存
      if (videoElement && isM3u8(lastPlayedUrlRef.current)) {
        // 使用HlsPlayer的detach方法释放资源
        HlsPlayer.detach(videoElement);
      }
    }

    // 清理状态引用
    isPlayerReadyRef.current = false;
    isSwitchingRef.current = false;
    isProcessingQueueRef.current = false;
    pendingSwitchRef.current = null; // 清理待处理的切换请求
    switchQueueRef.current = []; // 清理切换队列
  }, []);

  useEffect(() => {
    
    if (!artRef.current || !playList.length) return;

    // 确保先销毁旧实例
    destroyPlayer();

    // 初始化播放器并存储初始URL
    const initialUrl = playList[initialIndex].url;
    lastPlayedUrlRef.current = initialUrl;
    // 初始化当前索引引用
    currentEpisodeIndexRef.current = initialIndex;

    // 初始化配置
    const options: Option = {
      container: artRef.current,
      url: initialUrl,
      customType: {
        m3u8: optimizedHls,
      },
      volume: 0.7,
      isLive: false,
      muted: false,
      autoplay: false,
      pip: false,
      autoSize: false,
      autoMini: false,
      screenshot: true,
      setting: true,
      loop: false,
      flip: true,
      playbackRate: true,
      aspectRatio: true,
      fullscreen: true,
      fullscreenWeb: false,
      subtitleOffset: false,
      miniProgressBar: true,
      mutex: true,
      backdrop: true,
      playsInline: true,
      autoPlayback: true,
      airplay: true,
      theme: '#ff5f57',
      lang: 'zh-cn',
      hotkey: true,
      moreVideoAttr: {
        crossOrigin: 'anonymous',
      },
      settings: [],
      icons: {
        loading: '<svg xmlns="http://www.w3.org/2000/svg" width="2.5rem" height="2.5rem" viewBox="0 0 24 24" fill="none" stroke="#ff5f57" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="animate-spin"><path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"></path></svg>',
        state: '<svg xmlns="http://www.w3.org/2000/svg" width="2.5rem" height="2.5rem" viewBox="0 0 24 24" fill="none" stroke="#ffffff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3" fill="rgba(255,255,255,0.2)"></polygon></svg>',
      },
    };

    // 创建播放器实例
    playerRef.current = new Artplayer(options);
    console.log('播放器已初始化，当前选集索引:', initialIndex, '当前播放URL:', initialUrl);

    // 监听播放器准备就绪事件
    playerRef.current.on('ready', () => {
      console.log('播放器已准备就绪');
      isPlayerReadyRef.current = true;
      isSwitchingRef.current = false;
      isProcessingQueueRef.current = false;

      // 确保全屏功能正常工作
      if (playerRef.current) {
        // 重新绑定全屏相关事件，确保功能正常
        const player = playerRef.current;

        // 清理旧的事件监听器，避免重复绑定
        player.off('fullscreen');
        player.off('fullscreenWeb');

        // 监听全屏状态变化
        player.on('fullscreen', (state: boolean) => {
          console.log('全屏状态变化:', state);
        });

        // 监听网页全屏状态变化
        player.on('fullscreenWeb', (state: boolean) => {
          console.log('网页全屏状态变化:', state);
        });
      }

      // 处理待处理的切换请求（兼容旧的单个请求方式）
      if (pendingSwitchRef.current) {
        const pendingSwitch = pendingSwitchRef.current;
        console.log('播放器就绪，处理待处理的切换请求:', pendingSwitch);

        // 清除待处理请求
        pendingSwitchRef.current = null;

        // 添加到队列中处理
        switchQueueRef.current.push({
          url: pendingSwitch.url,
          name: pendingSwitch.name,
          index: pendingSwitch.index,
          callback: () => {
            // 切换完成后的回调
            const tryToPlay = () => {
              if (playerRef.current && !playerRef.current.playing) {
                console.log('尝试播放待处理的视频...');
                playerRef.current.play().catch(err => {
                  console.error('自动播放失败:', err);
                });
              }
            };

            // 延迟尝试播放
            setTimeout(tryToPlay, 300);
          }
        });
      }

      // 处理队列中的切换请求
      console.log('播放器就绪，开始处理切换队列，队列长度:', switchQueueRef.current.length);
      setTimeout(() => processQueue(), 100);
    });

    // 监听播放器销毁事件
    playerRef.current.on('destroy', () => {
      console.log('播放器已销毁');
      isPlayerReadyRef.current = false;
      isSwitchingRef.current = false;
      isProcessingQueueRef.current = false;
      pendingSwitchRef.current = null; // 清理待处理的切换请求
      switchQueueRef.current = []; // 清理切换队列
    });

    // 不自动尝试播放，而是等待外部信号

    // 监听来自播放列表的切换事件
    const handleSwitchEpisode = (e: CustomEvent) => {
      const eventUrl = e.detail?.url;
      const eventIndex = e.detail?.index;
      const eventName = e.detail?.name;

      if (!eventUrl) {
        console.error('切换选集错误: 未提供URL');
        return;
      }

      // 记录详细的选集切换日志
      console.log('收到切换选集事件:', {
        url: eventUrl,
        index: eventIndex,
        name: eventName,
        currentPlayIndex: initialIndex,
        currentUrlRef: lastPlayedUrlRef.current,
        isPlayerReady: isPlayerReadyRef.current
      });

      // 如果当前URL已经是目标URL，不执行切换避免重复播放
      if (lastPlayedUrlRef.current === eventUrl) {
        console.log('相同URL，跳过切换:', eventUrl);
        return;
      }

      // 如果播放器未就绪，保存待处理的切换请求
      if (!isPlayerReadyRef.current || !playerRef.current) {
        console.log('播放器未就绪，保存待处理的切换请求');
        pendingSwitchRef.current = {
          url: eventUrl,
          name: eventName,
          index: eventIndex
        };

        // 更新引用，确保状态同步
        if (eventIndex !== undefined) {
          currentEpisodeIndexRef.current = eventIndex;
        }
        lastPlayedUrlRef.current = eventUrl;

        return;
      }

      // 切换到新的URL
      console.log('切换到选集:', eventUrl, '索引:', eventIndex);

      // 使用安全切换方法
      const switchSuccess = safeSwitch(eventUrl, () => {
        // 切换完成后的回调
        const tryToPlay = () => {
          if (playerRef.current && !playerRef.current.playing) {
            console.log('尝试播放切换后的视频...');
            playerRef.current.play().catch(err => {
              console.error('自动播放失败:', err);
            });
          }
        };

        // 延迟尝试播放
        setTimeout(tryToPlay, 300);
      });

      if (switchSuccess) {
        // 更新最近播放的URL引用
        lastPlayedUrlRef.current = eventUrl;

        // 更新当前播放索引的引用
        if (eventIndex !== undefined) {
          currentEpisodeIndexRef.current = eventIndex;
        } else {
          // 如果没有提供索引，通过URL查找
          const foundIndex = playList.findIndex(item => item.url === eventUrl);
          if (foundIndex !== -1) {
            currentEpisodeIndexRef.current = foundIndex;
          }
        }

        console.log('更新播放器内部索引引用:', currentEpisodeIndexRef.current);
      } else {
        console.error('切换失败，播放器状态异常');
      }
    };

    window.addEventListener('switchEpisode', handleSwitchEpisode as EventListener);

    // 清理函数
    return () => {
      window.removeEventListener('switchEpisode', handleSwitchEpisode as EventListener);
      destroyPlayer();
    };
    
  }, [playList, initialIndex, destroyPlayer]);

  // 在组件卸载时清理所有HLS实例资源
  useEffect(() => {
    // 监听清理事件
    const handleCleanupRequest = (e: CustomEvent) => {
      console.log('收到清理播放器请求:', e.detail);
      destroyPlayer();
    };
    
    // 监听开始播放事件
    const handleStartPlayback = (e: CustomEvent) => {
      console.log('收到开始播放请求:', e.detail);
      if (playerRef.current && !playerRef.current.playing) {
        console.log('手动开始播放视频');
        playerRef.current.play().catch(err => {
          console.error('手动播放失败:', err);
          // 不使用静音播放，由用户手动点击播放按钮
        });
      }
    };
    
    window.addEventListener('cleanupPlayer', handleCleanupRequest as EventListener);
    window.addEventListener('startPlayback', handleStartPlayback as EventListener);
    
    return () => {
      // 清理事件监听
      window.removeEventListener('cleanupPlayer', handleCleanupRequest as EventListener);
      window.removeEventListener('startPlayback', handleStartPlayback as EventListener);
      
      // 组件卸载时清理所有HLS资源
      destroyPlayer();
      HlsPlayer.destroy();
    };
  }, [destroyPlayer]);

  // 单独监听currentIndex的变化，方便调试并同步到ref
  useEffect(() => {
    console.log('currentIndex已更新:', activeIndex, '播放列表长度:', playList.length);
    // 同步currentIndex到引用中，确保它们一致
    if (activeIndex !== currentEpisodeIndexRef.current) {
      console.log('同步currentIndex到引用:', activeIndex, '(原值:', currentEpisodeIndexRef.current, ')');
      currentEpisodeIndexRef.current = activeIndex;
    }
  }, [activeIndex, playList.length]);

  // 处理视频结束自动播放下一集
  useEffect(() => {
    // 定义视频结束事件处理函数
    const handleVideoEnded = () => {
      // 从引用中获取当前索引，避免依赖可能过时的状态
      const currentPlayingIndex = currentEpisodeIndexRef.current;
      
      console.log('视频结束:', {
        urlFromRef: lastPlayedUrlRef.current,
        indexFromRef: currentPlayingIndex,
        hookCurrentIndex: activeIndex,
        totalEpisodes: playList.length
      });
      
      // 确保索引有效
      if (currentPlayingIndex >= 0 && currentPlayingIndex < playList.length - 1) {
        const nextItem = playList[currentPlayingIndex + 1];
        const nextIndex = currentPlayingIndex + 1;
        
        if (playerRef.current && nextItem?.url) {
          console.log('自动切换到下一集:', nextItem.name, nextItem.url);

          // 使用安全切换方法
          const switchSuccess = safeSwitch(nextItem.url, () => {
            // 切换完成后自动播放
            const tryToPlay = () => {
              if (playerRef.current) {
                console.log('尝试播放下一集...');
                playerRef.current.play().catch(err => {
                  console.error('自动播放失败:', err);
                });
              }
            };

            // 延迟尝试播放
            setTimeout(tryToPlay, 500);
          });

          if (switchSuccess) {
            // 更新索引引用和URL引用
            currentEpisodeIndexRef.current = nextIndex;
            lastPlayedUrlRef.current = nextItem.url;

            // 通知父组件选集已更改
            onEpisodeChange?.(nextIndex);

            // 使用 history API 更新URL，确保状态同步
            if (videoId) {
              const newUrl = `/detail/${videoId}-${nextIndex}.html`;
              window.history.pushState({ path: newUrl }, '', newUrl);
            }

            // 调用handleEpisodeClick更新应用状态
            handleEpisodeClick(nextItem);

            // 发送自定义事件通知UI组件更新选中状态
            const event = new CustomEvent('episodeChanged', {
              detail: {
                index: nextIndex,
                url: nextItem.url,
                name: nextItem.name
              }
            });
            window.dispatchEvent(event);
          } else {
            console.error('自动播放下一集失败，播放器状态异常');
          }
        }
      }
    };
    
    // 如果播放器存在且已初始化，绑定事件处理
    if (playerRef.current) {
      console.log('重新绑定video:ended事件，currentIndex:', activeIndex, 'refIndex:', currentEpisodeIndexRef.current);
      // 先移除旧的事件处理，避免重复绑定
      playerRef.current.off('video:ended');
      // 然后添加新的事件处理
      playerRef.current.on('video:ended', handleVideoEnded);
    }
    
    return () => {
      if (playerRef.current) {
        playerRef.current.off('video:ended');
      }
    };
  }, [activeIndex, playList, handleEpisodeClick, onEpisodeChange, videoId, safeSwitch]);

  // 添加键盘事件监听器，用于处理'n'键播放下一集
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // 如果按下的是'n'键
      if (e.key === 'n' || e.key === 'N') {
        // // 检查播放器是否准备就绪且未在切换中
        // if (!isPlayerReadyRef.current || isSwitchingRef.current) {
        //   console.log('播放器未准备就绪或正在切换中，忽略快捷键操作');
        //   return;
        // }

        // 从引用中获取当前索引
        const currentPlayingIndex = currentEpisodeIndexRef.current;

        // 确保索引有效且有下一集可播放
        if (currentPlayingIndex >= 0 && currentPlayingIndex < playList.length - 1) {
          const nextItem = playList[currentPlayingIndex + 1];
          const nextIndex = currentPlayingIndex + 1;

          if (playerRef.current && nextItem?.url) {
            console.log('按下n键，切换到下一集:', nextItem.name, nextItem.url);

            // 使用安全切换方法
            const switchSuccess = safeSwitch(nextItem.url, () => {
              // 切换完成后自动播放
              const tryToPlay = () => {
                if (playerRef.current) {
                  console.log('尝试播放下一集...');
                  playerRef.current.play().catch(err => {
                    console.error('自动播放失败:', err);
                  });
                }
              };

              // 延迟尝试播放
              setTimeout(tryToPlay, 500);
            });

            if (switchSuccess) {
              // 更新索引引用和URL引用
              currentEpisodeIndexRef.current = nextIndex;
              lastPlayedUrlRef.current = nextItem.url;

              // 通知父组件选集已更改
              onEpisodeChange?.(nextIndex);

              // 使用 history API 更新URL，确保状态同步
              if (videoId) {
                const newUrl = `/detail/${videoId}-${nextIndex}.html`;
                window.history.pushState({ path: newUrl }, '', newUrl);
              }

              // 调用handleEpisodeClick更新应用状态
              handleEpisodeClick(nextItem);

              // 发送自定义事件通知UI组件更新选中状态
              const event = new CustomEvent('episodeChanged', {
                detail: {
                  index: nextIndex,
                  url: nextItem.url,
                  name: nextItem.name
                }
              });
              window.dispatchEvent(event);
            } else {
              console.error('快捷键切换失败，播放器状态异常');
            }
          }
        } else {
          console.log('已经是最后一集或索引无效');
        }
      }
    };
    
    // 添加键盘事件监听器
    window.addEventListener('keydown', handleKeyDown);
    
    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [playList, handleEpisodeClick, onEpisodeChange, videoId, safeSwitch]);

  return (
    <div className="w-full">
      <div ref={artRef} className="w-full aspect-video bg-black lg:rounded-l-lg shadow-lg"></div>
    </div>
  );
}
